package br.pucrs.lognplay.service;

import java.util.List;

import javax.ejb.Stateless;

import br.pucrs.lognplay.entity.Client;
import br.pucrs.lognplay.repository.ClientRepository;
import br.pucrs.lognplay.repository.RepositoryManager;

@Stateless
public class ClientManagementServiceBean implements ClientManagementService {

	public void mergeClient(Client client) throws ServiceException {
		try {
			RepositoryManager.beginTransaction();
			ClientRepository clientRepository = RepositoryManager.getClientRepository();
			clientRepository.merge(client);
			RepositoryManager.commitTransaction();
		} catch (Exception e) {
			RepositoryManager.rollbackTransaction();
			throw new ServiceException("Error on merge a client", e);
		}
	}

	public Client getClientById(String id) throws ServiceException {
		try {
			RepositoryManager.beginTransaction();
			ClientRepository clientRepository = RepositoryManager.getClientRepository();
			Client client = clientRepository.get(id);
			RepositoryManager.commitTransaction();
			return client;
		} catch (Exception e) {
			RepositoryManager.rollbackTransaction();
			throw new ServiceException("Error on get a client by id", e);
		}
	}

	public List<Client> listAllClients() throws ServiceException {
		try {
			RepositoryManager.beginTransaction();
			ClientRepository clientRepository = RepositoryManager.getClientRepository();
			List<Client> clients = clientRepository.listAll();
			RepositoryManager.commitTransaction();
			return clients;
		} catch (Exception e) {
			RepositoryManager.rollbackTransaction();
			throw new ServiceException("Error on list all clients", e);
		}
	}
}
